package com.yaoweigroup.community.adapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.yaoweigroup.community.R;
import com.yaoweigroup.community.enity.BBSContent;
import com.yaoweigroup.community.enity.ReplyDetail;
import com.yaoweigroup.community.ui.home.GroupDetailActivity.MyImageGetter;
import com.yaoweigroup.community.ui.home.GroupDetailActivity.MyImageGetter.URLDrawable;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.MD5;

public class ReplyAdapter extends BaseAdapter {

	private Context context;
	private List<ReplyDetail> list;
	private LayoutInflater mInflater;

	public ReplyAdapter(Context context, List<ReplyDetail> list) {
		mInflater = LayoutInflater.from(context);
		this.context = context;
		this.list = list;
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		Holder holder;
		if (convertView == null) {
			holder = new Holder();
			convertView = mInflater.inflate(R.layout.adapter_bbs_item, null);
			convertView.setTag(holder);
			holder.icon_iv = (ImageView) convertView.findViewById(R.id.icon_iv);
			holder.name_tv = (TextView) convertView.findViewById(R.id.name_tv);
			holder.click_tv = (TextView) convertView
					.findViewById(R.id.click_tv);
			holder.content_tv = (TextView) convertView
					.findViewById(R.id.content_tv);
			holder.time_tv = (TextView) convertView.findViewById(R.id.time_tv);
			holder.replay_tv = (TextView) convertView
					.findViewById(R.id.replay_tv);

		} else {
			holder = (Holder) convertView.getTag();
		}

		holder.icon_iv.setVisibility(View.GONE);
		ReplyDetail content = list.get(position);
		String name = content.getRealName();
		if (name == null) {
			name = content.getUserName();
		}
		holder.name_tv.setText(name);
		String contentStr = content.getReplyContent();
		if (contentStr == null)
			contentStr = "暂无内容";

		holder.content_tv.setText(Html.fromHtml(content.getReplyContent(),
				new MyImageGetter(context, holder.content_tv), null));
		holder.time_tv.setText(content.getReplyDate());
		holder.replay_tv.setVisibility(View.GONE);
		holder.click_tv.setVisibility(View.GONE);
		return convertView;
	}

	public final class Holder {

		TextView name_tv;
		ImageView icon_iv;
		TextView click_tv;
		TextView content_tv;
		TextView time_tv;
		TextView replay_tv;
	}

	public void setDataChange(List<ReplyDetail> list) {
		this.list = list;
		notifyDataSetChanged();
	}

	public class MyImageGetter implements ImageGetter {

		private Context context;
		private TextView tv;

		public MyImageGetter(Context context, TextView tv) {
			this.context = context;
			this.tv = tv;
		}

		@Override
		public Drawable getDrawable(String source) {
			// TODO Auto-generated method stub
			// 将source进行MD5加密并保存至本地
			if (!source.startsWith("http")) {
				source = "http://www.smartcity.sh" + source;
			}
			LogUtil.d("wxf", "source=" + source);
			String imageName = MD5.encode(source);
			String sdcardPath = Environment.getExternalStorageDirectory()
					.toString(); // 获取SDCARD的路径
			// 获取图片后缀名
			String[] ss = source.split("\\.");
			String ext = ss[ss.length - 1];

			// 最终图片保持的地址
			String savePath = sdcardPath + "/" + context.getPackageName() + "/"
					+ imageName + "." + ext;

			File file = new File(savePath);
			if (file.exists()) {
				// 如果文件已经存在，直接返回
				Drawable drawable = Drawable.createFromPath(savePath);
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight());
				return drawable;
			}

			// 不存在文件时返回默认图片，并异步加载网络图片
			Resources res = context.getResources();
			URLDrawable drawable = new URLDrawable(
					res.getDrawable(R.drawable.bucket_no_picture));
			new ImageAsync(drawable).execute(savePath, source);
			return drawable;

		}

		private class ImageAsync extends AsyncTask<String, Integer, Drawable> {

			private URLDrawable drawable;

			public ImageAsync(URLDrawable drawable) {
				this.drawable = drawable;
			}

			@Override
			protected Drawable doInBackground(String... params) {

				InputStream in = null;// TODO Auto-generated method stub
				try {
					String savePath = params[0];
					String url = params[1];

					// 获取网络图片
					HttpGet http = new HttpGet(url);
					HttpClient client = new DefaultHttpClient();
					HttpResponse response = (HttpResponse) client.execute(http);
					BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
							response.getEntity());
					in = bufferedHttpEntity.getContent();

					if (in == null)
						return drawable;

					File file = new File(savePath);
					String basePath = file.getParent();
					File basePathFile = new File(basePath);
					if (!basePathFile.exists()) {
						basePathFile.mkdirs();
					}
					file.createNewFile();
					FileOutputStream fileout = new FileOutputStream(file);
					byte[] buffer = new byte[4 * 1024];
					while (in.read(buffer) != -1) {
						fileout.write(buffer);
					}
					fileout.flush();
					Drawable mDrawable = Drawable.createFromPath(savePath);
					return mDrawable;

				} catch (Exception e) {
					try {
						if (in != null)
							in.close();
					} catch (Exception e2) {
						// TODO: handle exception
					}
				}
				return drawable;
			}

			@Override
			protected void onPostExecute(Drawable result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null) {
					drawable.setDrawable(result);
					tv.setText(tv.getText()); // 通过这里的重新设置 TextView 的文字来更新UI
				}
			}

		}

		public class URLDrawable extends BitmapDrawable {

			private Drawable drawable = null;

			public URLDrawable(Drawable defaultDraw) {
				if (defaultDraw == null)
					return;
				setDrawable(defaultDraw);
			}

			private void setDrawable(Drawable nDrawable) {
				if (nDrawable == null)
					return;
				drawable = nDrawable;
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight());
				setBounds(0, 0, drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight());
			}

			@Override
			public void draw(Canvas canvas) {
				if (drawable != null) {
					drawable.draw(canvas);
				}
			}

		}
	}
}
